package com.lej.core.utils

import com.tencent.mmkv.MMKV
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty


/**
 * Created by 大哥哥 on 2020/02/15 0015.
 * @version 0.2（删除Json字符串存储功能 尽量不要拿KV存储Json or xml字符串）
 */
class KV<T>(var default: T) : ReadWriteProperty<Any?, T> {

    companion object {
        val kv: MMKVUtils by lazy { MMKVUtils.getInstance() }
        fun clear() {
            MMKV.defaultMMKV().clearAll()
        }
    }

    override fun getValue(thisRef: Any?, property: KProperty<*>): T {
        return kv.decodeIt(property.name, default)
    }

    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        kv.encodeIt(property.name, value)
    }
}


private fun <U> MMKVUtils.decodeIt(name: String, default: U): U = with(this) {
    val res: Any = when (default) {
        is Long -> getLong(name, default)
        is String -> getString(name, default)
        is Int -> getInt(name, default)
        is Boolean -> getBoolean(name, default)
        is Float -> getFloat(name, default)
        is Double -> getDouble(name, default)
        is ByteArray -> getBytes(name, default)
        else -> {
            throw IllegalArgumentException("not support type ${default.toString()}")
        }
    }
    @Suppress("UNCHECKED_CAST")
    return@with res as U
}

private fun <T> MMKVUtils.encodeIt(name: String, value: T) =
    when (value) {
        is Long -> put(name, value)
        is String -> put(name, value)
        is Int -> put(name, value)
        is Boolean -> put(name, value)
        is Float -> put(name, value)
        is Double -> put(name, value)
        is ByteArray -> put(name, value)
        else -> {
            throw IllegalArgumentException("not support type ${value.toString()}")
        }
    }
